import axios from 'axios'
import { ElNotification, ElMessage } from 'element-plus'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: 'https://admin.tnaot.com',
  // 超时
  timeout: 10000
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.state || 1;
    
    if (code !== 1) {
      ElNotification.error({ title: `操作失败: ${res.data.error_msg}` })
      return Promise.reject('error')
    } else {
      return Promise.resolve(res.data.result)
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "tanot.com 接口连接异常";
    } else if (message.includes("timeout")) {
      message = "tanot.com 接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "tanot.com 接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage({ message: message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)

export default service
